<?php
namespace App\Models\V1;

use Illuminate\Database\Eloquent\Model;
use DB;
use Illuminate\Database\Eloquent\SoftDeletes;

class LiveModel extends Model
{
    protected $table = 'live';
    use SoftDeletes;
    protected $dates    = ['deleted_at'];
    protected $fillable = ['live_title', 'chat_group_id', 'face_img', 'preview_video', 'total_user_number', 'current_user_number', 'viewed_times', 'begin_time', 'is_end', 'description', 'is_show_desc', 'ad_img', 'ad_text', 'is_show_ad', 'is_show', 'notice', 'live_type', 'teacher_phone', 'app', 'strem', 'push_msg', 'is_completed','live_status', 'link_url', 'live_url', 'add_view_times', 'is_notice','live_detail_view_times', 'ali_live_view_times'];

    /**
     * 获得直播详情
     * @param integer $liveId 直播ID
     * @return array
     * */
    public function get_live_detail($liveId)
    {
        $liveDetail = $this->find($liveId)->toArray();

        return $liveDetail;
    }


    /**
     * 获取最新直播
     * */
    public function get_last_live_id()
    {
        $liveInfo = $this->where(['is_show' => 1])
            ->where('deleted_at')
            ->orderBy('id', 'desc')
            ->first();

        if ($liveInfo) {
            return $liveInfo->id;
        } else {
            return 0;
        }
    }

    /**
     * 添加浏览日志
     * @param integer $liveId 直播ID
     * @param integer $userId 用户ID
     * @param integer $type 记录类型
     * */
    public function add_viewed_log($liveId, $userId, $type)
    {
        $data = [
            'live_id'    => $liveId,
            'user_id'    => $userId,
            'type'       => $type,
            'created_at' => date_time()
        ];
        DB::table('live_viewed_log')->insert($data);
    }


    /**
     * 获取直播列表
     * */
    public function get_lives($keywords)
    {
        if ($keywords) {
            $lives = $this->where('live_title', 'like', '%' . $keywords . '%')->where('deleted_at')->orderBy('id', 'desc')->paginate(20);
        } else {
            $lives = $this->where('deleted_at')->orderBy('id', 'desc')->paginate(20);
        }

        return $lives;
    }
}
